from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
from django.shortcuts import get_object_or_404
from django.db import transaction
from .models import Project
from .serializers import ProjectSerializer, ProjectDetailSerializer, ProjectCreateSerializer
from logwisdomhub.response import ApiResponse, ErrorCode
import logging

logger = logging.getLogger(__name__)

class ProjectViewSet(viewsets.ModelViewSet):
    serializer_class = ProjectSerializer
    permission_classes = [IsAuthenticated]
    
    def get_queryset(self):
        return Project.objects.filter(owner=self.request.user)
    
    def get_serializer_class(self):
        if self.action == 'create':
            return ProjectCreateSerializer
        elif self.action in ['retrieve', 'list']:
            return ProjectDetailSerializer
        return ProjectSerializer
    
    def list(self, request, *args, **kwargs):
        """获取项目列表"""
        try:
            queryset = self.filter_queryset(self.get_queryset())
            page = self.paginate_queryset(queryset)
            
            if page is not None:
                serializer = self.get_serializer(page, many=True)
                paginated_data = self.get_paginated_response(serializer.data).data
                return ApiResponse.paginated_success(paginated_data, "获取项目列表成功")
            
            serializer = self.get_serializer(queryset, many=True)
            return ApiResponse.success({
                'results': serializer.data,
                'count': len(serializer.data)
            }, "获取项目列表成功")
            
        except Exception as e:
            logger.error(f"获取项目列表失败: {str(e)}")
            return ApiResponse.error(
                f"获取项目列表失败: {str(e)}", 
                ErrorCode.DATABASE_ERROR,
                http_status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )
    
    def create(self, request, *args, **kwargs):
        """创建项目"""
        try:
            with transaction.atomic():
                serializer = self.get_serializer(data=request.data)
                if serializer.is_valid():
                    # 检查项目名称是否已存在
                    if Project.objects.filter(
                        owner=request.user, 
                        name=serializer.validated_data['name']
                    ).exists():
                        return ApiResponse.error(
                            "项目名称已存在",
                            ErrorCode.PROJECT_NAME_EXISTS,
                            http_status=status.HTTP_400_BAD_REQUEST
                        )
                    
                    project = serializer.save(owner=request.user)
                    return ApiResponse.success(
                        ProjectDetailSerializer(project).data,
                        "项目创建成功",
                        ErrorCode.SUCCESS,
                        status.HTTP_201_CREATED
                    )
                else:
                    return ApiResponse.error(
                        "数据验证失败",
                        ErrorCode.VALIDATION_ERROR,
                        serializer.errors,
                        status.HTTP_400_BAD_REQUEST
                    )
                    
        except Exception as e:
            logger.error(f"创建项目失败: {str(e)}")
            return ApiResponse.error(
                f"创建项目失败: {str(e)}", 
                ErrorCode.DATABASE_ERROR,
                http_status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )
    
    def retrieve(self, request, *args, **kwargs):
        """获取项目详情"""
        try:
            instance = self.get_object()
            serializer = self.get_serializer(instance)
            return ApiResponse.success(serializer.data, "获取项目详情成功")
        except Project.DoesNotExist:
            return ApiResponse.error(
                "项目不存在", 
                ErrorCode.NOT_FOUND_ERROR, 
                http_status=status.HTTP_404_NOT_FOUND
            )
        except Exception as e:
            logger.error(f"获取项目详情失败: {str(e)}")
            return ApiResponse.error(
                f"获取项目详情失败: {str(e)}", 
                ErrorCode.DATABASE_ERROR,
                http_status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )
    
    def update(self, request, *args, **kwargs):
        """更新项目"""
        try:
            with transaction.atomic():
                partial = kwargs.pop('partial', False)
                instance = self.get_object()
                serializer = self.get_serializer(instance, data=request.data, partial=partial)
                
                if serializer.is_valid():
                    # 如果更新名称，检查是否重复
                    if 'name' in serializer.validated_data:
                        if Project.objects.filter(
                            owner=request.user,
                            name=serializer.validated_data['name']
                        ).exclude(id=instance.id).exists():
                            return ApiResponse.error(
                                "项目名称已存在",
                                ErrorCode.PROJECT_NAME_EXISTS,
                                http_status=status.HTTP_400_BAD_REQUEST
                            )
                    
                    project = serializer.save()
                    return ApiResponse.success(
                        ProjectDetailSerializer(project).data,
                        "项目更新成功"
                    )
                else:
                    return ApiResponse.error(
                        "数据验证失败",
                        ErrorCode.VALIDATION_ERROR,
                        serializer.errors,
                        status.HTTP_400_BAD_REQUEST
                    )
                    
        except Project.DoesNotExist:
            return ApiResponse.error(
                "项目不存在", 
                ErrorCode.NOT_FOUND_ERROR, 
                http_status=status.HTTP_404_NOT_FOUND
            )
        except Exception as e:
            logger.error(f"更新项目失败: {str(e)}")
            return ApiResponse.error(
                f"更新项目失败: {str(e)}", 
                ErrorCode.DATABASE_ERROR,
                http_status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )
    
    def destroy(self, request, *args, **kwargs):
        """删除项目"""
        try:
            with transaction.atomic():
                instance = self.get_object()
                project_name = instance.name
                instance.delete()
                return ApiResponse.success(
                    {'deleted_project': project_name}, 
                    "项目删除成功"
                )
        except Project.DoesNotExist:
            return ApiResponse.error(
                "项目不存在", 
                ErrorCode.NOT_FOUND_ERROR, 
                http_status=status.HTTP_404_NOT_FOUND
            )
        except Exception as e:
            logger.error(f"删除项目失败: {str(e)}")
            return ApiResponse.error(
                f"删除项目失败: {str(e)}", 
                ErrorCode.DATABASE_ERROR,
                http_status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )
    
    @action(detail=True, methods=['post'])
    def regenerate_api_key(self, request, pk=None):
        """重新生成API密钥"""
        try:
            with transaction.atomic():
                project = self.get_object()
                old_key = project.api_key[:8] + '...'  # 只显示前8位
                new_api_key = project.regenerate_api_key()
                
                return ApiResponse.success({
                    'api_key': new_api_key,
                    'project_id': project.id,
                    'project_name': project.name,
                    'old_key_preview': old_key
                }, "API密钥重新生成成功")
                
        except Project.DoesNotExist:
            return ApiResponse.error(
                "项目不存在", 
                ErrorCode.NOT_FOUND_ERROR, 
                http_status=status.HTTP_404_NOT_FOUND
            )
        except Exception as e:
            logger.error(f"重新生成API密钥失败: {str(e)}")
            return ApiResponse.error(
                "重新生成API密钥失败", 
                ErrorCode.API_KEY_GENERATION_FAILED,
                http_status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )
    
    @action(detail=True, methods=['get'])
    def api_key(self, request, pk=None):
        """获取API密钥"""
        try:
            project = self.get_object()
            return ApiResponse.success({
                'api_key': project.api_key,
                'project_id': project.id,
                'project_name': project.name,
                'created_at': project.created_at
            }, "获取API密钥成功")
            
        except Project.DoesNotExist:
            return ApiResponse.error(
                "项目不存在", 
                ErrorCode.NOT_FOUND_ERROR, 
                http_status=status.HTTP_404_NOT_FOUND
            )
        except Exception as e:
            logger.error(f"获取API密钥失败: {str(e)}")
            return ApiResponse.error(
                f"获取API密钥失败: {str(e)}", 
                ErrorCode.DATABASE_ERROR,
                http_status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )